package com.iyao_app.Friends;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.IMUser;
import com.iyao_app.entry.User;
import com.iyao_app.im.adapter.ChatAdapter;
import com.iyao_app.im.nimsdk.utils.NimHistorySDK;
import com.iyao_app.im.nimsdk.utils.NimMessageSDK;
import com.iyao_app.im.nimsdk.utils.UIUtils;
import com.iyao_app.im.presenter.ChatPresenter;
import com.iyao_app.im.view.ChatView;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.PickImageLoader;
import com.iyao_app.util.ToastUtil;
import com.iyao_app.util.UserUtils;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChatActivity extends BaseActivityWithHead implements ChatView, TextView.OnEditorActionListener {

    @BindView(R.id.chatRecyclerView)
    RecyclerView chatRecyclerView;
    @BindView(R.id.et_msg)
    EditText etMsg;
    @BindView(R.id.typeface_border)
    TextView mTypefaceBorder;

    private ChatPresenter mChatPresenter;
    private String username;
    private ChatAdapter chatAdapter;
    private List<IMMessage> emMessageList = new ArrayList<IMMessage>();

    private String headImage = null;

    private PopupWindow mPopWindow;

    //消息列表及监听
    private Observer<IMMessage> mMsgStatusObserver;
    private Observer<List<IMMessage>> mIncomingMessageObserver;

    //获取历史消息
    private IMMessage mAnchor;
    private QueryDirectionEnum mDirection = QueryDirectionEnum.QUERY_OLD;//查询以前的消息
    private static final int LOAD_MESSAGE_COUNT = 2000;
    private boolean mFirstLoad = true;
    private boolean mRemote = false;

    //    public String mSessionId;//单聊的联系人的id，群聊是群id
    public SessionTypeEnum mSessionType = SessionTypeEnum.P2P;

    final static int CAMERA_RESULT = 0;//声明一个常量，代表结果码
    private static final int IMAGE = 1;
    private Button button;//声明一个Button对象

    private Runnable mCvMessageScrollToBottomTask = new Runnable() {
        @Override
        public void run() {
            chatRecyclerView.smoothScrollToPosition(emMessageList.size());
        }
    };
    private User user;
    private String nickname;
    private String favicon;

    final int IMAGE_PICKER = 1;

    private ImagePicker imagePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        username = intent.getStringExtra("username");
        nickname = intent.getStringExtra("nickname");
        favicon = intent.getStringExtra("favicon");

        //传用户的名字
        setTitleTV(nickname);

        etMsg.setOnEditorActionListener(this);

        registerAllObserver();

        if (chatAdapter == null) {
            chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            chatAdapter = new ChatAdapter(this, emMessageList);
            chatRecyclerView.setAdapter(chatAdapter);
        } else {
            chatAdapter.notifyDataSetChanged();
        }

        loadHistoryMsgFromLocal();
        if (chatRecyclerView != null){
            cvScrollToBottom();
        }

        initPicker();

    }

    private void initPicker() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);   //显示拍照按钮
        imagePicker.setCrop(false);         //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);
        imagePicker.setSaveRectangle(true);//是否按矩形区域保存
        imagePicker.setSelectLimit(1);     //选中数量限制
    }

    public boolean checkPermission(@NonNull String permission) {
        return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imagePicker.takePicture(this, ImagePicker.REQUEST_CODE_TAKE);
            } else {
                ToastUtil.showToast(this, "权限被禁止，无法打开相机");
            }
        }
    }
    public static final int REQUEST_PERMISSION_CAMERA = 0x02;

    @OnClick(R.id.typeface_border)
    public void onViewClicked() {
        showPopupWindow();
    }

    //发送文本消息
    private void sendMsg() {
        String msg = etMsg.getText().toString().trim();
        if (TextUtils.isEmpty(msg)) {
            ToastUtil.showToast(this,"消息不能为空");
            return;
        }

        user = DbUtil.getUser();

        IMMessage textMessage = MessageBuilder.createTextMessage(username, SessionTypeEnum.P2P, msg);

        Map<String,Object> extMap=new HashMap<>();
        extMap.put("fromNickName",user.nickname);
        extMap.put("fromAvatar", user.avatarUrl);
        extMap.put("toAvatar",favicon);
        extMap.put("toNickName",nickname);
        LogUtil.e("===textMessage==>"+textMessage.toString()+"===msg==>"+msg);
        textMessage.setRemoteExtension(extMap);
        emMessageList.add(textMessage);

        String sessionId = username;
        IMUser imUser = new IMUser();
        imUser.userId = sessionId;
        imUser.head = favicon;
        imUser.nickName = nickname;
        UserUtils.addUser(imUser);

        NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
        afterInitData(emMessageList, false);
        if (emMessageList.size() != 0){
            cvScrollToBottom();
        }
        etMsg.getText().clear();
    }

    /**
     * 发送图片消息
     */
    private void sendImagesMsg(File image) {
        if (image.exists()){
            LogUtil.e("==image="+image.getAbsolutePath());
        }
        IMMessage message = MessageBuilder.createImageMessage(username, mSessionType, image, image.getName());

        Map<String,Object> extMap=new HashMap<>();
        user = DbUtil.getUser();
        extMap.put("fromNickName",user.nickname);
        extMap.put("fromAvatar", user.avatarUrl);
        extMap.put("toAvatar",favicon);
        extMap.put("toNickName",nickname);
        message.setRemoteExtension(extMap);
        emMessageList.add(message);

        String sessionId = username;
        IMUser imUser = new IMUser();
        imUser.userId = sessionId;
        imUser.head = favicon;
        imUser.nickName = nickname;
        UserUtils.addUser(imUser);
        NIMClient.getService(MsgService.class).sendMessage(message, false);

        afterInitData(emMessageList, false);
        if (emMessageList.size() != 0){
            cvScrollToBottom();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMessage emMessage) {
        //判断当前接收到的消息是否是发送给当前聊天对象的
        //if (username.equals(emMessage.getUserName())){
        //更新RecyclerView
        mChatPresenter.initChatData(username, false);
        // }
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        if (i == EditorInfo.IME_ACTION_SEND) {
            sendMsg();
            return true;
        }
        return false;
    }

    @Override
    public void afterInitData(List<IMMessage> emMessageList, boolean isSmooth) {
        LogUtil.e("mm", String.valueOf(emMessageList.size()));
        if (chatAdapter == null) {
            chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            chatAdapter = new ChatAdapter(this, emMessageList);
            chatRecyclerView.setAdapter(chatAdapter);
            chatAdapter.notifyDataSetChanged();
        } else {
            chatAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void updateChatData(boolean success, String msg, IMMessage emMessage) {
        if (!success) {
//            showToast(msg);
        }
        chatAdapter.notifyDataSetChanged();
        chatRecyclerView.smoothScrollToPosition(Integer.MAX_VALUE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁消息状态监听和消息接收监听
        unRegisterAllObserver();
    }

    private void registerAllObserver() {
        observeMsgStatus();
        observeReceiveMessage();
    }

    private void unRegisterAllObserver() {
        NimMessageSDK.observeMsgStatus(mMsgStatusObserver, false);
        NimMessageSDK.observeReceiveMessage(mIncomingMessageObserver, false);
    }

    /**
     * 注册消息状态监听
     */
    private void observeMsgStatus() {
        mMsgStatusObserver = new Observer<IMMessage>() {
            @Override
            public void onEvent(IMMessage imMessage) {
                if (NimMessageSDK.isCurrentSessionMessage(imMessage, username, mSessionType)) {
                    onMessageStatusChange(imMessage);
                    afterInitData(emMessageList, false);
                }
            }
        };
        NimMessageSDK.observeMsgStatus(mMsgStatusObserver, true);
    }

    private int getItemIndex(String uuid) {
        for (int i = 0; i < emMessageList.size(); i++) {
            IMMessage message = emMessageList.get(i);
            if (TextUtils.equals(message.getUuid(), uuid)) {
                return i;
            }
        }
        return -1;
    }

    private void onMessageStatusChange(IMMessage message) {
        int index = getItemIndex(message.getUuid());
        if (index >= 0 && index < emMessageList.size()) {
            IMMessage msg = emMessageList.get(index);
            msg.setStatus(message.getStatus());
            msg.setAttachStatus(message.getAttachStatus());
            chatAdapter.notifyItemChanged(index);
        }
    }

    /**
     * 注册消息接收监听
     */
    private void observeReceiveMessage() {
        mIncomingMessageObserver = new Observer<List<IMMessage>>() {
            @Override
            public void onEvent(List<IMMessage> imMessages) {

                LogUtil.e("ss", String.valueOf(emMessageList.size()));
                LogUtil.e("ee", "data is null: "+ (imMessages == null));
                if (imMessages == null || imMessages.isEmpty()) {
                    return;
                }
                for (IMMessage abc:imMessages){

                    String content = abc.getFromAccount();
                    LogUtil.e("ee", "content的内容是: "+ content);//content反出来的是发消息用户的id
                    LogUtil.e("==abc===>"+abc.getRemoteExtension());
                }

                //筛选出当前会话的消息
                List<IMMessage> currentMsgList = new ArrayList<>();
                for (IMMessage msg : imMessages) {
                    if (NimMessageSDK.isCurrentSessionMessage(msg, username, mSessionType)) {
                        currentMsgList.add(msg);

                    }
                }
                LogUtil.e("aa",currentMsgList.toString());

                //获取未插入新消息前的最后一个可见位置

                List<IMMessage> data = chatAdapter.getData();
                int size = data.size();
                int theLastOnePosition = size - 1;

                chatAdapter.addMoreData(currentMsgList);

                chatAdapter.notifyDataSetChanged();

                //如果当前列表处于最新消息，则自动滚动到底部
                int lastVisibleItemPosition = ((LinearLayoutManager) chatRecyclerView.getLayoutManager()).findLastVisibleItemPosition();
                if (lastVisibleItemPosition == theLastOnePosition)
                    cvScrollToBottom();
//                }

            }
        };
        //观察消息
        NimMessageSDK.observeReceiveMessage(mIncomingMessageObserver, true);
    }

    /**
     * 消息列表滚动至最后
     */
    private void cvScrollToBottom() {
        UIUtils.postTaskDelay(mCvMessageScrollToBottomTask, 100);
    }

    /**
     * 拍照的PopupWindow
     */
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.chat_popupwindow, null);
        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        //设置各个控件的点击响应
        ImageButton tv1 = (ImageButton) contentView.findViewById(R.id.ib_photograph);
        ImageButton tv2 = (ImageButton) contentView.findViewById(R.id.ib_photoalbum);
        ImageButton tv3 = (ImageButton) contentView.findViewById(R.id.ib_gengduo);
        //拍照
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!(checkPermission(Manifest.permission.CAMERA))) {
                    ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
                } else {
                    imagePicker.takePicture(ChatActivity.this, ImagePicker.REQUEST_CODE_TAKE);
                }
            }
        });
        //调取相册
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Intent intent = new Intent(ChatActivity.this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
            }
        });
        //更多
        tv3.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.e("更多");
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_chat, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 180);

    }

    /**
     * 用onActivityResult()接收传回的图像，当用户拍完照片，或者取消后，系统都会调用这个函数
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem imageItem = images.get(0);

                File file = new File( imageItem.path);
                if (file.exists()){
                    sendImagesMsg(file);
                    LogUtil.e("==file.exists()==");
                }else {
                    LogUtil.e("==!file.exists()==");
                }

            } else {
                //Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == RESULT_OK) {
            if (requestCode == ImagePicker.REQUEST_CODE_TAKE) {

                headImage = imagePicker.getTakeImageFile().getAbsolutePath();

                LogUtil.e("======ImageUtils.IMAGE_FILE + headImage========",ImageUtils.IMAGE_FILE + headImage);

                File file = new File( headImage);
                if (file.exists()){
                    sendImagesMsg(file);
                    LogUtil.e("==file.exists()==");
                }else {
                    LogUtil.e("==!file.exists()==");
                }
            }
        }
    }

    /**
     * 获取锚点
     */
    private IMMessage getAnchor() {
        if (emMessageList.size() == 0) {
            return mAnchor == null ? MessageBuilder.createEmptyMessage(username, mSessionType, 0) : mAnchor;
        } else {
            int index = (mDirection == QueryDirectionEnum.QUERY_NEW ? emMessageList.size() - 1 : 0);
            return emMessageList.get(index);
        }
    }

    /**
     * 从本地获取历史消息
     */
    private void loadHistoryMsgFromLocal() {
        LogUtil.e("ee","从本地获取历史消息");
        mDirection = QueryDirectionEnum.QUERY_OLD;
        mRemote = false;
        NimHistorySDK.queryMessageListEx(getAnchor(), mDirection, LOAD_MESSAGE_COUNT, true).setCallback(loadFromRemoteCallback);
    }


    /**
     * 从服务器获取旧的历史消息
     */
    private void loadHistoryMsgFromRemote() {
        LogUtil.e("ee","从服务器获取旧的历史消息");
        mDirection = QueryDirectionEnum.QUERY_OLD;
        mRemote = true;
        NimHistorySDK.pullMessageHistory(getAnchor(), LOAD_MESSAGE_COUNT, true).setCallback(loadFromRemoteCallback);
    }

    private boolean mIsFirstLoadHistory = true;

    RequestCallback<List<IMMessage>> loadFromRemoteCallback = new RequestCallbackWrapper<List<IMMessage>>() {
        @Override
        public void onResult(int code, List<IMMessage> result, Throwable exception) {
            LogUtil.e("code", result.toString());
            if (code != ResponseCode.RES_SUCCESS || exception != null) {
                return;
            }

            if (result == null)
                return;

            //是第一次加载本地历史消息时，不需要从服务器加载数据
            if (mIsFirstLoadHistory) {
                mIsFirstLoadHistory = false;
            }
            //如果从本地获取消息已经没有了，则从服务器获取消息
            else if (result.size() == 0 && !mRemote) {
                loadHistoryMsgFromRemote();
                return;
            }

            onMessageLoaded(result);
        }
    };


    /**
     * 历史消息加载处理
     *
     * @param messages
     */
    private void onMessageLoaded(List<IMMessage> messages) {
        if (mRemote) {
            Collections.reverse(messages);
        }

        if (mFirstLoad && emMessageList.size() > 0) {
            // 在第一次加载的过程中又收到了新消息，做一下去重
            for (IMMessage message : messages) {
                for (IMMessage item : emMessageList) {
                    if (item.isTheSame(message)) {
                        chatAdapter.removeItem(item);
                        break;
                    }
                }
            }
        }

        if (mFirstLoad && mAnchor != null) {
            chatAdapter.addLastItem(mAnchor);
        }

        if (mDirection == QueryDirectionEnum.QUERY_NEW) {
            chatAdapter.addMoreData(messages);
        } else {
            chatAdapter.addNewData(messages);
        }

        if (mFirstLoad) {
            cvScrollToBottom();
        } else {

        }
        mFirstLoad = false;
    }

}
